package com.xr.core.system.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xr.core.system.common.annotation.OperationLogAnno;
import com.xr.core.system.common.base.Result;
import com.xr.core.system.common.constants.Constant;
import com.xr.core.system.common.enums.OperationType;
import com.xr.core.system.common.utils.ThreadLocalUtil;
import com.xr.core.system.entity.userModule.LoginInfoVO;
import com.xr.core.system.entity.userModule.User;
import com.xr.core.system.service.PermissionService;
import com.xr.core.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 登录相关
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/login")
public class LoginController {

    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @PostMapping("/login")
    @OperationLogAnno(module = "登录模块", type = OperationType.LOGIN, desc = "用户登录")
    public Result<Object> login(@Validated @RequestBody LoginInfoVO loginInfoVO) {
        SaSession tokenSession = StpUtil.getTokenSession();
        Object attribute = tokenSession.get(Constant.CAPTCHA_SESSION_KEY);
        if (attribute == null) {
            return Result.error("验证码已失效，请刷新页面后重试！");
        }
        if (!StrUtil.equalsIgnoreCase((CharSequence) attribute, loginInfoVO.getVerificationCode())) {
            return Result.error("验证码不正确！");
        }
        tokenSession.delete(Constant.CAPTCHA_SESSION_KEY);
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getAccount, loginInfoVO.getAccount()).eq(User::getEnable, true);
        User user = userService.getOne(wrapper);
        if (user == null) {
            return Result.error("账户或密码错误");
        }
        String password = user.getPassword();
        Assert.notBlank(password, "密码不能为空");
        boolean b = DigestUtil.bcryptCheck(loginInfoVO.getPassword(), password);
        if (b) {
            Long userId = user.getId();
            StpUtil.login(userId);
            ThreadLocalUtil.setUser(user);
            return Result.success(StpUtil.getTokenValue());
        }
        return Result.error("账号或密码错误");
    }

    /**
     * 获取当前登录人的页面权限
     */
    @GetMapping("/permission")
    public Result<List<String>> getPermissions() {
        return Result.success(permissionService.getAllPermissionUrlByUserId());
    }

    /**
     * 获取当前登录人的按钮权限
     */
    @GetMapping("/btnPermission")
    public Result<List<String>> getBtnPermission() {
        return Result.success(permissionService.getAllBtnPermissionByUserId());
    }

    /**
     * 注销登录
     */
    @GetMapping("/signOut")
    public Result<Object> signOut() {
        StpUtil.logout();
        return Result.success();
    }

}
